import React, { ReactText, useEffect, useState } from "react";
import { View, Text, Radio, RadioGroup } from "@tarojs/components";
import "./index.scss";
import { AtInput, AtTextarea, AtForm } from "taro-ui";
import { AtMessage } from "taro-ui";
import { success, error, getLocalStore, $emit } from "../../utils/util";
import classnames from 'classnames'
import { getRes, request } from "../../utils/request";
import { BaseRes } from "../../api/types";
import Taro from '@tarojs/taro';
import { checkIsRep, getUserInfoById, signUp } from "../../api/user";
export default function SForm() {
  const openid = getLocalStore('openid');
  // 姓名
  const [name, setName] = useState<string>("");

  // 性别
  const [sex, setSex] = useState<string>("男");

  // 电话号码
  const [phone, setPhone] = useState<string>("");

  // 学号
  const [stuNum, setstuNum] = useState<string>('');
  // 学院
  const [aca, setAca] = useState<string>("");
  // 专业
  const [major, setMajor] = useState<string>("");
  // 方向
  const [dire, setDire] = useState<string>("前端");

  // 简单的自我介绍
  const [selfIntro, setSelfIntro] = useState<string>("");

  // qq
  const [qq, setQq] = useState<string>('')

  // 动画的激活项
  const [activeIndex, setActiveIndex] = useState<number>();


  // 激活的点
  const [activeList, setActiveList] = useState<number[]>([]);

  // 设置初始值
  useEffect(() => {
    (async () => {
      const { code, data } = await getUserInfoById(openid);
      if (code == '1') {
        if (data[0]) {
          const { name, sex, phoneNum, sno, college, major, direction, introduce, qq } = data[0];
          console.log(data[0], sex, direction);
          setName(name);
          setSex(sex);
          setPhone(phoneNum);
          setstuNum(sno);
          setAca(college);
          setMajor(major);
          setDire(direction);
          setSelfIntro(introduce);
          setQq(qq);
        }
      }
    })()
  }, [])


  // formList字段
  interface Field { tip: string; val: string; name: string; fn: Function; type: 'number' | 'text'; length: number }
  const formList: Field[] = [
    {
      tip: "姓名",
      val: name,
      name: "name",
      fn: setName,
      type: 'text',
      length: 20
    },
    {
      tip: "电话号码",
      val: phone,
      name: "phone",
      fn: setPhone,
      type: 'number',
      length: 11
    },
    {
      tip: "学号",
      val: stuNum,
      name: "stuNUm",
      fn: setstuNum,
      type: 'number',
      length: 20
    },
    {
      tip: "学院",
      val: aca,
      name: "aca",
      fn: setAca,
      type: 'text',
      length: 20
    },
    {
      tip: "专业",
      val: major,
      name: "major",
      fn: setMajor,
      type: 'text',
      length: 20
    },
    {
      tip: 'qq',
      val: qq,
      name: 'qq',
      fn: setQq,
      type: 'number',
      length: 20
    }
  ];
  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    // 检验数据的合法性
    if (validateField()) {
      // 通过校验
      const { confirm: isAgree } = await Taro.showModal({
        title: '提示',
        content: '为了方便后续的面试及考核，小程序将会存储你所填写的报名信息'
      })
      if (isAgree) {
        // 1. 校验是否重复提交
        const { code, data } = await checkIsRep(openid);
        console.log(code, data, '校验')
        if (code == '1') {
          const { confirm } = await Taro.showModal({
            title: '提示',
            content: data
          })
          if (confirm) {
            // 点击确定，去报名
            const { code, data } = await signUp({
              college: aca,
              direction: dire,
              introduce: selfIntro,
              phoneNum: phone,
              sno: stuNum,
              major,
              sex,
              name,
              openid,
              qq,
            })
            if (code == '1') {
              // 报名成功
              // 1. 清空表单
              // resetForm();

              // 2. 弹出信息
              success(data.data);

              // 3. 更新状态
              $emit('signCb')

              // 4. 跳转到状态
              setTimeout(() => {
                Taro.switchTab({
                  url: '/pages/status/index'
                })
              }, 1000)
            } else if (code == '-1') {
              // 弹出错误
              const vals = Object.values(data);
              // 只弹出一个错误
              error(vals[0])
            }
          }
        }
      }
    }
  };

  /**
   * 重置表单
   */
  const resetForm = () => {
    setName('');
    setPhone('');
    setstuNum('');
    setAca('');
    setMajor('');
    setSelfIntro('');
    setQq('');
  }


  /**
   * 检验数据是否合法
   */
  const validateField = (): boolean => {
    let type: boolean = false;
    if (!name) {
      error("请输入姓名");
    } else if (!phone) {
      error("请输入手机号码");
    } else if (!stuNum) {
      error("请输入学号");
    } else if (!aca) {
      error("请输入学院");
    } else if (!major) {
      error("请输入专业");
    } else if (!qq) {
      error('请输入qq');
    }
    else if (!selfIntro) {
      error("请输入自我介绍");
    }
    else {
      type = true;
    }
    return type;
  };

  // 增加动画
  const addAnime = (i: number) => {
    // console.log('聚焦了, 设置动画');
    setActiveIndex(i);
    setActiveList([...activeList, i]);
  }

  // 移除动画
  const rmAnime = (val: string) => {
    setActiveIndex(-1); // 离开时清除文本框的聚焦
    if (!val) {
      activeList.pop();
      setActiveList(activeList);
    }
  }

  // 性别切换
  const handleSexChange = (e: any) => {
    const val: string = e.detail.value;
    console.log(val);
    setSex(val);
  };
  // 方向切换
  const handleDireChange = (e: any) => {
    const val: string = e.detail.value;
    setDire(val);
  };


  // 获取当前时间
  let isChecked = false
  var nowTime = new Date().getTime()
  const checkedTime = Date.parse('2022/05/30 18:00:00')
  if (nowTime > checkedTime) {
    // 说明已经过了审核周期，正常显示
    isChecked = true
  }

  return (
    <>
      {
        isChecked ? (
          <AtForm className="form" >
            {
              formList.map((item, index) => {
                const { tip, val, name, fn } = item;
                return (
                  <View className={classnames('form-item', { 'active-item': activeList.includes(index) || val })} key={index}>
                    <View className="tip">{tip}</View>
                    <AtInput
                      type={item.type}
                      className={classnames('inp', { 'inp-active': index === activeIndex })}
                      name={name}
                      value={val}
                      onBlur={() => rmAnime(val)}
                      onFocus={() => addAnime(index)}
                      onChange={(val: ReactText) => {
                        // 检验通过
                        fn(val as string);
                        return val;
                      }}
                    />
                  </View>
                );
              })
            }
            < AtMessage />
            <View className="form-item">
              <Text className="spe">性别: </Text>
              <RadioGroup className="rd" onChange={handleSexChange}>
                <Radio className="radio" value={"男"} checked={sex === '男'} color="#a29bfe">
                  男
                </Radio>
                <Radio className="radio" value={"女"} checked={sex === '女'} color="#a29bfe">
                  女
                </Radio>
              </RadioGroup>
            </View>
            <View className="form-item">
              <Text className="spe">方向: </Text>
              <RadioGroup className="rd" onChange={handleDireChange}>
                <Radio
                  className="radio"
                  value={"前端"}
                  checked={dire === '前端'}
                  color="#a29bfe"
                >
                  前端
                </Radio>
                <Radio
                  className="radio"
                  value={"后台"}
                  checked={dire === '后台'}
                  color="#a29bfe"
                >
                  后台
                </Radio>
              </RadioGroup>
            </View>

            <View className="form-item">
              <View className="spe">个人介绍</View>
              <AtTextarea
                value={selfIntro}
                count={false}
                placeholder="自我介绍，对这个方向的看法等等"
                onChange={(val: string) => {
                  setSelfIntro(val);
                }}
              ></AtTextarea>
            </View>
            <View className="form-item">
              <View className="btn" onClick={handleSubmit}>
                提交
              </View>
            </View>
          </AtForm>
        ) : '小程序暂时不支持报名，请到QQ群中填问卷星！'
      }
    </>
  );
}
